<template>
    <div>
        <div class="i-layout-page-header">
            <PageHeader title="员工信息" hidden-breadcrumb/>
        </div>
        <!--    公共筛选查询区域-->
        <Card :bordered="false" dis-hover>
            <!--筛选查询条件区域-->
            <Form ref="form" :model="data" :rules="rules" :label-width="labelWidth" :label-position="labelPosition">
                <Row :gutter="24" type="flex" justify="end">

                    <Col v-bind="grid">
                        <FormItem label="用户名称：">
                            <Input v-model="data.nickName" placeholder="请输入关键字"/>
                        </FormItem>
                    </Col>
                    <Col v-bind="grid">
                        <FormItem label="所属部门：" >
                            <Select v-model="data.dept" placeholder="请选择部门">
                                <Option value="1">研发部</Option>
                                <Option value="2">市场部门</Option>
                                <Option value="3">测试部门</Option>
                                <Option value="4">财务部门</Option>
                                <Option value="5">运维部门</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <template v-if="collapse">
                        <Col v-bind="grid">
                            <FormItem label="开始时间：">
                                <Date-picker v-model="data.startTime"
                                             format="yyyy-MM-dd HH:mm:ss"
                                             type="datetime" placeholder="开始日期" v-width="'100%'"></Date-picker>
                            </FormItem>
                        </Col>
                        <Col v-bind="grid">
                            <FormItem label="结束时间：">
                                <Date-picker
                                        v-model="data.endTime"
                                        format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束日期"
                                        v-width="'100%'"></Date-picker>
                            </FormItem>
                        </Col>
                        <Col v-bind="grid">
                        </Col>
                    </template>
                    <Col v-bind="grid" class="ivu-text-right">
                        <FormItem>
                            <Button type="primary" @click="getData">查询</Button>
                            <Button class="ivu-ml-8" @click="handleReset">重置</Button>
                            <a v-font="14" class="ivu-ml-8" @click="collapse = !collapse">
                                <template v-if="!collapse">
                                    展开 <Icon type="ios-arrow-down" />
                                </template>
                                <template v-else>
                                    收起 <Icon type="ios-arrow-up" />
                                </template>
                            </a>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <!--新增-->
            <div class="buttonContain">
                <Button @click="handleOpenCreate" type="primary">新增
                </Button>
            </div>
        </Card>
        <!--数据渲染区域-->
        <div class="i-table-no-border">
            <Table
                    ref="table"
                    :columns="columnslist"
                    :data="dataWithPage"
                    :loading="loading"
            >
                <template slot-scope="{ row }" slot="status">
                    <Switch v-model="row.status"
                            :before-change="handleBeforeChange"
                    />
                </template>
                <template slot-scope="{ row }" slot="status">
                    <Badge v-if="row.status === 0" status="error" text="禁用"/>
                    <Badge v-if="row.status === 1" status="success" text="启用"/>
                </template>
                <!--考勤情况（1：迟到，2：早退，3：迟到+早退，4：旷工）-->
                <template slot-scope="{ row }" slot="clockInfo">
                    <Badge v-if="row.clockInfo === ''" status="Default" text="无"></Badge>
                    <Badge v-if="row.clockInfo === '1'" status="success" text="正常"></Badge>
                    <Badge v-if="row.clockInfo === '2'" status="warning" text="迟到"></Badge>
                    <Badge v-if="row.clockInfo === '3'" status="warning" text="早退"></Badge>
                    <Badge v-if="row.clockInfo === '4'" color="red"  text="迟到+早退"></Badge>
                    <Badge v-if="row.clockInfo === '5'" color="pink" text="旷工"></Badge>
                </template>
                <template slot-scope="{ row}" slot="action">
                    <a @click="showDetail(row.clockId)">详情</a>
                    <Divider type="vertical" />
                    <!--<a @click="handleEdit(row.clockId)" :style="{'color':'#4AABF2'}">编辑</a>
                    <Divider type="vertical"/>-->
                    <a @click="handleDelete(row.clockId)" :style="{'color':'red'}">删除</a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page :total="limitData.length" show-elevator :current.sync="current" show-total/>
            </div>

        </div>
        <Modal v-model="showCreate" title="新增" @on-ok="handleCreate" width="800" :loading="creating"
        >
            <Form ref="create" :model="createData" :rules="createRules" :label-width="120">

                <FormItem label="公告类型：" prop="noticeType" label-for="noticeType">
                    <RadioGroup v-model="createData.noticeType" element-id="noticeType">
                        <Radio label="1">公告</Radio>
                        <Radio label="2">通知</Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
        </Modal>
    </div>

</template>

<script>
    import {mapState} from 'vuex';
    import Attendance from "@/api/Attendance";

    export default {
        data() {
            return {
                collapse: false,
                grid: {
                    xl: 8,
                    lg: 8,
                    md: 12,
                    sm: 24,
                    xs: 24
                },
                courentTime:'',
                editMesId: '',
                updateIndex: -1,
                showCreate: false,
                creating: true,
                switch1: false,
                data: {
                    nickName: '',
                    clockInfo: '',
                },
                createData: {
                    noticeTitle: '',
                    content: '',
                    createBy: '',
                    noticeType: '',
                },
                //验证规则
                rules: {},
                //验证规则
                createRules: {
                    noticeTitle: [
                        {required: true, message: '公告标题', trigger: 'blur'}
                    ],
                    content: [
                        {required: true, message: '内容', trigger: 'blur'}
                    ],
                    createBy: [
                        {required: true, message: '操作人员', trigger: 'blur'}
                    ],
                    noticeType: [
                        {required: true, message: '公告类型', trigger: 'change'}
                    ],

                },
                dayak: [],
                count: 10,
                current: 1,
                list: [],
                size: 10,
                datalist: [],
                columnslist: [
                    {
                        title: '序号',
                        key: 'clockId',
                        minWidth: 50
                    },
                    {
                        title: '姓名',
                        key: 'nickName',
                        minWidth: 80

                    }, {
                        title: '部门',
                        key: 'clockAddress',
                        tooltip:true,
                        minWidth: 120

                    },{
                        title: '职位',
                        key: 'clockStartTime',
                        minWidth: 120

                    },{
                        title: '出勤天数',
                        key: 'clockEndTime',
                        minWidth: 120

                    },{
                        title: '休息天数',
                        slot: 'clockInfo',
                        minWidth: 80
                    },{
                        title: '迟到次数',
                        slot: 'clockInfo',
                        minWidth: 80
                    },{
                        title: '迟到时长',
                        slot: 'clockInfo',
                        minWidth: 80
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        align: 'center',
                        minWidth: 80
                    }
                ],
                loading: false,
            }
        },
        computed: {
            limitData() {
                let data = [...this.list];
                return data;
            },
            ...mapState('admin/layout', [
                'isMobile'
            ]),
            labelWidth() {
                return this.isMobile ? undefined : 100;
            },
            labelPosition() {
                return this.isMobile ? 'top' : 'right';
            },
            // 因为要动态计算总页数，所以还需要一个计算属性来返回最终给 Table 的 data
            dataWithPage() {
                const data = this.limitData;
                const start = this.current * this.size - this.size;
                const end = start + this.size;
                return [...data].slice(start, end);
            },
        },
        created() {
            this.getData();
        },
        mounted(){
            let _this = this; // 声明一个变量指向Vue实例this，保证作用域一致
            this.timer = setInterval(() => {
                _this.courentTime =this.getTime(); // 修改数据date
            }, 1000)
        },
        methods: {
            getCourentTime(){
                this.courentTime = new Date()
            },
            getTime(){
                var date1=new Date();
                var hours=date1.getHours();
                var minutes=date1.getMinutes();
                var seconds=date1.getSeconds();
                return hours+":"+minutes+":"+seconds
            },

            asyncOK() {
                setTimeout(() => {
                    this.modal6 = false;
                    alert(1)
                }, 2000);
            },
            handleBeforeChange(status) {
                return new Promise((resolve) => {
                    this.$Modal.confirm({
                        title: '切换确认',
                        content: '您确认要切换开关状态吗？',
                        onOk: () => {
                            resolve();
                        }
                    });
                });
            },
            /* change (status,index) {
                 this.switch1 = !this.switch1;
                 this.$Message.info('开关状态：' + status);
             },*/
            //获取数据，无条件则获取全部数据
            getData() {
                this.current = 1;
                this.loading = true;
                Attendance.findByPage({
                    clockType:1,//考勤类型（1：内勤打卡，2：外勤打卡）
                    clockInfo:this.data.clockInfo,
                    nickName:this.data.nickName,
                })
                    .then(res => {
                        // 返回数据
                        console.log(res);
                        this.list = res;
                        this.loading = false;
                        this.data.clockInfo = '';
                        this.data.nickName = '';
                    })
                    .catch(err => {
                        // 异常情况
                    })

            },
            handleReset() {
                this.$refs.form.resetFields();
                this.$emit('on-reset');
            },
            /*pc端模拟打卡*/
            handleOpenCreate() {
                Attendance.insertAttendance({
                    clockType:1,//考勤类型（1：内勤打卡，2：外勤打卡）
                    userId:7,
                    nickName:"小风",
                    clockAddress:"江苏省南京市江宁区"
                })
                    .then(res => {
                        // 返回数据
                        this.$Message.success("打卡成功");
                        this.getData();
                    })
                    .catch(err => {
                        // 异常情况
                        this.$Message.error("打卡异常");
                    })
            },


            //编辑
            handleEdit(clockId) {
                this.editclockId = clockId;
                Attendance.getMessageInfoById({
                    clockId
                })
                    .then(res => {
                        // 返回数据
                        this.createData = res;
                    })
                    .catch(err => {
                        // 异常情况
                    })
                this.updateIndex = 11;
                this.showCreate = true;
            },
            // 新增数据
            handleCreate() {
                this.$refs.create.validate((valid) => {
                    if (valid) {
                        if (this.updateIndex < 0) {
                            // 新建
                            Attendance.addMessage({
                                noticeTitle: this.createData.noticeTitle,
                                content: this.createData.content,
                                createBy: this.createData.createBy,
                                noticeType: this.createData.noticeType,
                            })
                                .then(res => {
                                    // 返回数据
                                    this.$Message.success('创建成功');
                                    this.getData();
                                })
                                .catch(err => {
                                    // 异常情况
                                })

                        } else {
                            // 修改
                            Attendance.updateMessage({
                                clockId: this.editclockId,
                                noticeTitle: this.createData.noticeTitle,
                                content: this.createData.content,
                                createBy: this.createData.createBy,
                                noticeType: this.createData.noticeType,
                            })
                                .then(res => {
                                    // 返回数据
                                    this.$Message.success('修改成功');
                                    this.getData();
                                })
                                .catch(err => {
                                    // 异常情况
                                })

                        }

                        this.showCreate = false;
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    } else {
                        this.creating = false;
                        this.$nextTick(() => {
                            this.creating = true;
                        });
                    }
                });
            },

            // 详情
            showDetail(clockId) {
                this.$router.push({
                    path: '/attendance/attend-detail',
                    name: 'attend-detail',
                    query: {
                        clockId
                    }
                });
            },

            //删除
            handleDelete(clockId) {
                this.$Modal.confirm({
                    title: '删除',
                    content: '确定删除吗？',
                    onOk: () => {
                        Attendance.deleteById({
                            clockId
                        })
                            .then(res => {
                                // 返回数据
                                this.$Message.success('删除成功');
                                this.getData();
                            })
                            .catch(err => {
                                // 异常情况
                                this.$Message.error('删除失败');
                            })
                    }
                });
            }
        },
        beforeDestroy() {
            if (this.timer) {
                clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
            }
        }
    }
</script>


<style lang="less" scoped>
    .buttonContain {
        > button {
            width: 120px;
            height: 50px;
            font-size: 16px;
        }
    }

</style>
